"""
@Time   : 2023/7/14 10:34
@Author : 徐先生没洗头
@Email  : 2510317432@qq.com
@Desc   : 工具库
"""
import os
from datetime import timedelta, datetime

from dotenv import load_dotenv
from jose import jwt
from passlib.context import CryptContext

load_dotenv()

__pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')

SECRET_KEY = os.getenv("AUTH_SECRET_KEY")
ALGORITHM = os.getenv("AUTH_ALGORITHM")

# 24小时
ACCESS_TOKEN_EXPIRE_MINUTES = 1440


def verify_password(plain_password, hashed_password):
    """
    验证密码
    :param plain_password:
    :param hashed_password:
    :return:
    """
    return __pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    """
    生成hash密码
    :param password:
    :return:
    """
    return __pwd_context.hash(password)


def create_token(data: dict):
    """
    生成token
    :param data:
    :return:
    """
    to_encode = data.copy()
    expires_delta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    expire = datetime.now() + expires_delta
    to_encode.update({"exp": expire})
    encode_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encode_jwt


def extract_token(token: str):
    """
    解析token
    :param token:
    :return:
    """
    payload = jwt.decode(token, SECRET_KEY, algorithms=ALGORITHM)
    return payload.get('id')
